package com.ls.controller;

import com.ls.entity.Fruit;
import com.ls.service.FruitService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
public class FruitController {
    @Resource
    private FruitService fruitService;

    @RequestMapping(value = "/list")
    public String list(Model model) {
        List<Fruit> list = fruitService.getAll();

        if (list != null) {
            model.addAttribute("list", list);
        }

        return "list";
    }

    @RequestMapping(value = "/select/{id}")
    public String select(@PathVariable Integer id, Model model) {
        Fruit fruit = fruitService.getFruitById(id);

        if (fruit != null) {
            model.addAttribute("fruit", fruit);
        }

        return "select";
    }

    @RequestMapping(value = "/del/{id}")
    public void del(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        int ret = fruitService.del(id);

        if (ret > 0) {
            out.print("<script>");
            out.print("alert('删除成功!');");
            out.print("location.replace('http://localhost:8080/FruitSys/list');");
            out.print("</script>");
            out.flush();
            out.close();
        } else {
            out.print("<script>");
            out.print("alert('删除失败!');");
            out.print("window.history.back();");
            out.print("</script>");
            out.flush();
            out.close();
        }
    }
}